import { ref } from 'vue'
import { defineStore } from 'pinia'
import { login } from '@/api/user'
import { setItem, getItem, removeAllItem } from '@/utils/storage'
import md5 from 'md5'
import router from '@/router'
// 设置时间戳
import { setTimeStamp } from '@/utils/checkTime'
export const useUsersStore = defineStore('user', () => {
  let token = ref(getItem('token'))
  let avatar = ref(getItem('avatar'))

  async function userLogin(formVal) {
    const data = {
      username: formVal.username,
      password: md5(formVal.password)
    }
    const res = await login(data)

    if (res.code === 200) {
      token.value = res.data.token
      avatar.value = res.data.avatar
      setItem('token', token.value)
      setItem('avatar', avatar.value)
      setTimeStamp()
      return 'success'
    } else {
      return Promise.reject(new Error(res.data.message))
    }

  }

  function loginOut() {
    this.token = null
    this.avataravatar = null
    removeAllItem()
    router.push('/login')

  }

  return { token, avatar, userLogin, loginOut}
})
